﻿
namespace Behemoth.SharePoint.Services {

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.ServiceModel;
    using System.Text;

    /// <summary>
    /// Based on http://blogs.msdn.com/johnwpowell/archive/2009/01/03/consume-sharepoint-web-services-with-wcf-using-the-repository-gateway-mapper-domain-model-and-factory-design-patterns.aspx
    /// </summary>
    public class SPServicesClientFactory {

        // TODO refactor this... again
        #region Create instances of the various web services

        /// <summary>
        /// Creates a service client configured to call the SharePoint 2007 Webs service.
        /// </summary>
        /// <param name="webUrl">Url of the desired SPWeb object.</param>
        /// <returns>A service client configured to call Webs.asmx</returns>
        internal static Webs.WebsSoapClient CreateWebsClient(string webUrl) {
            // create the binding and proxy
            var endpointAddress = GetEndPointAddress(webUrl, SharePointService.Webs);
            var binding = SPServicesBindingFactory.CreateBindingInstance();
            var client = new Webs.WebsSoapClient(binding, endpointAddress);
            // set client to impersonate caller
            client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
            return client;
        }

        internal static Lists.ListsSoapClient CreateListsClient(string webUrl) {
            // create the binding and proxy
            var endpointAddress = GetEndPointAddress(webUrl, SharePointService.Lists);
            var binding = SPServicesBindingFactory.CreateBindingInstance();
            var client = new Lists.ListsSoapClient(binding, endpointAddress);
            // set client to impersonate caller
            client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
            return client;
        }

        #endregion

        private static EndpointAddress GetEndPointAddress(string webUrl, SharePointService service) {
            // generate the correct url for the desired web
            string sharePointServiceUrl = SPServiceUrl.Generate(webUrl, service);
            EndpointAddress endpointAddress = new EndpointAddress(sharePointServiceUrl);
            return endpointAddress;
        }

    } // class
} // namespace
